package com.resource.fxLoader
{
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.Loader;
	import flash.events.Event;
	import flash.events.IEventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.utils.ByteArray;
	
	/**
	 * 位图资源转换类 
	 * @author tangjian
	 * 
	 */	
	public class ImageResource extends AbstractResource
	{
		private var _loader:Loader;
		private var _bitmapData:BitmapData;
		public var completeFun:Function;
		
		public function ImageResource(target:IEventDispatcher=null)
		{
			super(target);
		}
		
		override public function parse(bytes:ByteArray):void
		{
			_loader = new Loader();
			_loader.contentLoaderInfo.addEventListener(Event.COMPLETE,onLoadComplete);
			_loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR,onLoadError);
			_loader.loadBytes(bytes);
		}
		
		override public function getBitmapdata():BitmapData
		{
			return _bitmapData;
		}
		
		private function onLoadError(event:IOErrorEvent):void
		{
			_loader.contentLoaderInfo.removeEventListener(Event.COMPLETE,onLoadComplete);
			_loader.contentLoaderInfo.removeEventListener(IOErrorEvent.IO_ERROR,onLoadError);
			this.dispatchEvent(new Event(Event.CANCEL));
		}
		
		private function onLoadComplete(event:Event):void
		{
			_loader.contentLoaderInfo.removeEventListener(Event.COMPLETE,onLoadComplete);
			_loader.contentLoaderInfo.removeEventListener(IOErrorEvent.IO_ERROR,onLoadError);
			_bitmapData = (_loader.content as Bitmap).bitmapData;
			
			if(completeFun != null)
				completeFun(_bitmapData);
			_loader.unload();
			//ObjectPool.disposeObject(_loader,Loader);
			_loader = null;
			this.dispatchEvent(event);
		}
	}
}